package com.daka.controller;

import com.daka.entity.*;
import com.daka.enumerate.StatusCode;
import com.daka.service.*;
import com.daka.vo.Page;
import com.daka.vo.request.BaseAddressRequestVo;
import com.daka.vo.request.ApproveRequestVo;
import com.daka.vo.response.BaseAddressResponsePo;
import com.daka.vo.response.passport.ApproveResponseVo;
import com.daka.vo.response.BaseAddressListVo;
import com.daka.vo.response.DataResponseVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by yangx
 * CreateTime: 2016/9/27 16:20
 */
@Controller
@RequestMapping("/address")
@Slf4j
public class ApproveController {

    @Resource
    private ApproveAddressService approveAddressService;
    @Resource
    private ApproveScoreService approveScoreService;
    @Resource
    private BaseAddressService baseAddressService;
    @Resource
    private UserService userService;
    @Resource
    private GroupService groupService;


    //列表
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/queryList", consumes = "application/json")
//    @Login
    public DataResponseVo<Object> queryList(@RequestBody ApproveRequestVo requestVo, HttpSession session) {
        String userId = "";
        if (requestVo.getUserId() == null) {
            userId = session.getAttribute("userId").toString();
        } else {
            userId = requestVo.getUserId().toString();
        }

        User user = userService.selectById(Integer.valueOf(userId));
        List<BaseAddress> list = new ArrayList<>();
        if (user.getRole() == 10) {
            //初审
            list = baseAddressService.selectFirst();
        } else if (user.getRole() == 20) {
            //专家
            list = baseAddressService.selectSecond();
        } else if (user.getRole() == 30) {
            //终审
            list = baseAddressService.selectThird();
        }
        List<BaseAddressListVo> listVos = new ArrayList<>();
        for (BaseAddress ba : list) {
            listVos.add(BaseAddressListVo.buildVO(ba));
        }
        return new DataResponseVo<>(StatusCode.SUCCESS.getStatusCode(), StatusCode.SUCCESS.getStatusMessage(), listVos);
    }


    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/queryDetail", consumes = "application/json")
//    @Login
    public DataResponseVo<Object> queryDetail(@RequestBody BaseAddress baseAddress, HttpSession session) {
        //基础地址的id
        if (baseAddress.getId() == null || baseAddress.getId() == 0) {
            return new DataResponseVo<>(StatusCode.PARAM_ERROR.getStatusCode(), StatusCode.PARAM_ERROR.getStatusMessage());
        }
        //基础地址
        BaseAddress baseAddress1 = baseAddressService.selectById(baseAddress.getId());
        //审批
        ApproveAddress approveAddress;
        try {
            approveAddress = approveAddressService.selectByAddress(baseAddress.getId());
        } catch (Exception e) {
            return new DataResponseVo<>(StatusCode.APPROVE_MORE.getStatusCode(), StatusCode.APPROVE_MORE.getStatusMessage());
        }
        ApproveResponseVo approveResponseVo = ApproveResponseVo.buildVO(baseAddress1, approveAddress);


        ApproveScore approveScore = new ApproveScore();
        approveScore.setApproveAddress(approveAddress.getId());
        approveScore.setOrgUserId(11);
        ApproveScore approveScore1 = approveScoreService.selectByOrg(approveScore);
        if (approveScore1 != null && approveScore1.getScore() != null) {
            approveResponseVo.setRemark1(approveScore1.getScore().toString());
        }
        approveScore.setOrgUserId(12);
        ApproveScore approveScore2 = approveScoreService.selectByOrg(approveScore);
        if (approveScore2 != null && approveScore2.getScore() != null) {
            approveResponseVo.setRemark2(approveScore2.getScore().toString());
        }
        approveScore.setOrgUserId(13);
        ApproveScore approveScore3 = approveScoreService.selectByOrg(approveScore);
        if (approveScore3 != null && approveScore3.getScore() != null) {
            approveResponseVo.setRemark3(approveScore3.getScore().toString());
        }

//        //专家评分
//        List<ApproveScore> list = approveScoreService.selectByApprove(approveAddress.getId());
//        if(list.size()==1){
//            approveResponseVo.setRemark1(list.get(0).getRemark());
//        }else if(list.size()==2){
//            approveResponseVo.setRemark1(list.get(0).getRemark());
//            approveResponseVo.setRemark2(list.get(1).getRemark());
//        }else if(list.size()==3){
//            approveResponseVo.setRemark1(list.get(0).getRemark());
//            approveResponseVo.setRemark2(list.get(1).getRemark());
//            approveResponseVo.setRemark3(list.get(2).getRemark());
//        }
        return new DataResponseVo<>(StatusCode.SUCCESS.getStatusCode(), StatusCode.SUCCESS.getStatusMessage(), approveResponseVo);
    }


    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/approve", consumes = "application/json")
//    @Login
    public DataResponseVo<Object> approve(@RequestBody ApproveRequestVo requestVo, HttpSession session) {

        String userId = "";
        if (requestVo.getUserId() == null) {
            userId = session.getAttribute("userId").toString();
        } else {
            userId = requestVo.getUserId().toString();
        }
        User user = userService.selectById(Integer.valueOf(userId));
        if (requestVo.getId() == null ) {
            return new DataResponseVo<>(StatusCode.PARAM_ERROR.getStatusCode(), StatusCode.PARAM_ERROR.getStatusMessage());
        }
        BaseAddress baseAddress = baseAddressService.selectById(requestVo.getId());
        if (baseAddress.getVerfierStatus() == 2) {
            return new DataResponseVo<>(StatusCode.APPROVE_TRUE.getStatusCode(), StatusCode.APPROVE_TRUE.getStatusMessage());
        }

        if (user.getRole() == 10) {
            //初审
            if (requestVo.getId() == null || requestVo.getRemark() == null || requestVo.getStatus() == null) {
                return new DataResponseVo<>(StatusCode.PARAM_ERROR.getStatusCode(), StatusCode.PARAM_ERROR.getStatusMessage());
            }

            ApproveAddress approveAddress = new ApproveAddress();
            approveAddress.setAddressId(baseAddress.getId());
            approveAddress.setApproveFirst(0);
            List<ApproveAddress> listAp = approveAddressService.selectByStatement(approveAddress);
            System.out.println("待审核的数据approveAddress的条数：" + listAp.size());

            if (listAp.size() != 1) {
                return new DataResponseVo<>(StatusCode.APPROVE_STATUS_ERROR.getStatusCode(), StatusCode.APPROVE_STATUS_ERROR.getStatusMessage());
            }
            approveAddress = listAp.get(0);
            if (requestVo.getStatus() == 1) {
                //初审通过
                approveAddress.setApproveFirst(1);
                approveAddress.setRemark(requestVo.getRemark());
                approveAddress.setUpdateTimeFirst(new Date());
                approveAddressService.update(approveAddress);
            } else if (requestVo.getStatus() == 0) {
                //驳回
                approveAddress.setApproveFirst(2);
                approveAddress.setRemark(requestVo.getRemark());
                approveAddress.setUpdateTimeFirst(new Date());
                approveAddressService.update(approveAddress);
                baseAddress.setVerfierStatus(-1);
                baseAddressService.update(baseAddress);
            }
        } else if (user.getRole() == 20) {
            //专家
            if (requestVo.getScore() == null ) {
                return new DataResponseVo<>(StatusCode.PARAM_ERROR.getStatusCode(), StatusCode.PARAM_ERROR.getStatusMessage());
            }
            //判断是否有可以评分的
            ApproveAddress approveAddress = new ApproveAddress();
            approveAddress.setAddressId(baseAddress.getId());
            approveAddress.setApproveFirst(1);
            approveAddress.setApproveSecond(0);
            List<ApproveAddress> listAp = approveAddressService.selectByStatement(approveAddress);
            System.out.println("专家打分的数据approveAddress的条数：" + listAp.size());
            if (listAp.size() != 1) {
                return new DataResponseVo<>(StatusCode.APPROVE_STATUS_ERROR.getStatusCode(), StatusCode.APPROVE_STATUS_ERROR.getStatusMessage());
            }
            approveAddress = listAp.get(0);
            //判断该专家是否点评过
            ApproveScore approveScore = new ApproveScore();
            approveScore.setApproveAddress(approveAddress.getId());
            approveScore.setOrgUserId(Integer.valueOf(userId));
            List<ApproveScore> listSc1 = approveScoreService.selectByStatement(approveScore);
            if (listSc1.size() > 0) {
                return new DataResponseVo<>(StatusCode.APPROVE_ONCE.getStatusCode(), StatusCode.APPROVE_ONCE.getStatusMessage());
            }
            //判断几条评分
            List<ApproveScore> listSc2 = approveScoreService.selectByApprove(approveAddress.getId());
            if (listSc2.size() > 2) {
                return new DataResponseVo<>(StatusCode.APPROVE_SCORE_OVER.getStatusCode(), StatusCode.APPROVE_SCORE_OVER.getStatusMessage());
            } else {
                approveScore.setRemark(requestVo.getScore().toString());
                approveScore.setScore(requestVo.getScore());
                approveScore.setCreateTime(new Date());
                approveScoreService.insert(approveScore);
                //总分
                approveAddress.setScore(approveAddress.getScore() + requestVo.getScore());
                if (listSc2.size() == 2) {
                    approveAddress.setScoreStatus(1);
                }
                approveAddressService.update(approveAddress);
            }
        } else if (user.getRole() == 30) {
            //终审
            if (requestVo.getRemark() == null || requestVo.getStatus() == null) {
                return new DataResponseVo<>(StatusCode.PARAM_ERROR.getStatusCode(), StatusCode.PARAM_ERROR.getStatusMessage());
            }
            ApproveAddress approveAddress = new ApproveAddress();
            approveAddress.setAddressId(baseAddress.getId());
            approveAddress.setApproveFirst(1);
            approveAddress.setApproveSecond(0);
            approveAddress.setScoreStatus(1);
            List<ApproveAddress> listAp = approveAddressService.selectByStatement(approveAddress);
            System.out.println("待审核的数据approveAddress的条数：" + listAp.size());
            if (listAp.size() != 1) {
                return new DataResponseVo<>(StatusCode.APPROVE_STATUS_ERROR.getStatusCode(), StatusCode.APPROVE_STATUS_ERROR.getStatusMessage());
            }
            approveAddress = listAp.get(0);
            if (requestVo.getStatus() == 1) {
                //终审通过
                approveAddress.setApproveSecond(1);
                approveAddress.setRemarkSecond(requestVo.getRemark());
                approveAddress.setUpdateTimeSecond(new Date());
                approveAddressService.update(approveAddress);
                baseAddress.setVerfierStatus(2);
                baseAddressService.update(baseAddress);
            } else if (requestVo.getStatus() == 0) {
                //驳回
                approveAddress.setApproveFirst(0);
                approveAddress.setApproveSecond(2);
                approveAddress.setRemarkSecond(requestVo.getRemark());
                approveAddress.setUpdateTimeSecond(new Date());
                approveAddressService.update(approveAddress);
//                baseAddress.setVerfierStatus(-1);
//                baseAddressService.update(baseAddress);
            }
        } else {
            return new DataResponseVo<>(StatusCode.NO_ACCESS.getStatusCode(), StatusCode.NO_ACCESS.getStatusMessage());
        }

        return new DataResponseVo<Object>(StatusCode.SUCCESS.getStatusCode(), StatusCode.SUCCESS.getStatusMessage());
    }



//    //列表
//    @ResponseBody
//    @RequestMapping(value = "/test1")
//    public void queryList1() throws SQLException {
//        /**
//         * sql
//         */
//        Connection conn = null;
//        String sql;
//        // MySQL的JDBC URL编写方式：jdbc:mysql://主机名称：连接端口/数据库的名称?参数=值
//        // 避免中文乱码要指定useUnicode和characterEncoding
//        // 执行数据库操作之前要在数据库管理系统上创建一个数据库，名字自己定，
//        // 下面语句之前就要先创建javademo数据库
//        String url = "jdbc:mysql://192.168.2.117:3306/jpress?"
//                + "user=root&password=123456&useUnicode=true&characterEncoding=UTF8";
//
//        try {
//            // 之所以要使用下面这条语句，是因为要使用MySQL的驱动，所以我们要把它驱动起来，
//            // 可以通过Class.forName把它加载进去，也可以通过初始化来驱动起来，下面三种形式都可以
//            Class.forName("com.mysql.jdbc.Driver");// 动态加载mysql驱动
//            // or:
//            // com.mysql.jdbc.Driver driver = new com.mysql.jdbc.Driver();
//            // or：
//            // new com.mysql.jdbc.Driver();
//
//            System.out.println("成功加载MySQL驱动程序");
//            // 一个Connection代表一个数据库连接
//            conn = DriverManager.getConnection(url);
//            // Statement里面带有很多方法，比如executeUpdate可以实现插入，更新和删除等
//            Statement stmt = conn.createStatement();
//            sql = "INSERT INTO jpress_content VALUES (" +
//                    "null, '上泰绅苑居民区志愿者工作站', '', null, null, '0', '/cms/attachment/20161012/2eb3936d360844e68f30d29e964b9d2a.jpg', 'jidi', null, '1', null, null, null, null, null, null, '0', 'normal', '0', '0', null, '0', '0.00', null, '0', null, '0', '2016-10-12 17:19:39', '2016-10-12 17:19:39', '上泰绅苑居民区志愿者工作站', null, null, null, null, null, null" +
//                    ");";
//            int result = stmt.executeUpdate(sql);// executeUpdate语句会返回一个受影响的行数，如果返回-1就没有成功
////            if (result != -1) {
////                System.out.println("创建数据表成功");
////                sql = "insert into student(NO,name) values('2012001','陶伟基')";
////                result = stmt.executeUpdate(sql);
////                sql = "insert into student(NO,name) values('2012002','周小俊')";
////                result = stmt.executeUpdate(sql);
////                sql = "select * from student";
////                ResultSet rs = stmt.executeQuery(sql);// executeQuery会返回结果的集合，否则返回空值
////                System.out.println("学号\t姓名");
////                while (rs.next()) {
////                    System.out
////                            .println(rs.getString(1) + "\t" + rs.getString(2));// 入如果返回的是int类型可以用getInt()
////                }
////            }
//        } catch (SQLException e) {
//            System.out.println("MySQL操作错误");
//            e.printStackTrace();
//        } catch (Exception e) {
//            e.printStackTrace();
//        } finally {
//            conn.close();
//        }
//    }


    //列表
    @ResponseBody
    @RequestMapping(value = "/queryAddressList",method = RequestMethod.POST,produces = "application/json; charset=UTF-8")
    public DataResponseVo<Object> queryApList(@RequestBody BaseAddressRequestVo po) {
//        System.out.println(po.toString());
//        if(po.getServiceFieldString()!=null && po.getServiceFieldString()!=""){
//            po.setServiceField(po.getServiceFieldString().split(","));
//        }
        //接收一个baseType
        if(po.getBaseType()!="" && po.getBaseType()!=null){
            switch (po.getBaseType()){
                case "all": //全部
                    po.setType(0);
                    break;
                case "technology": //科技
                    po.setType(1);
                    break;
                case "education": //教育
                    po.setType(2);
                    break;
                case "culture": //文化
                    po.setType(3);
                    break;
                case "healthcare": //卫生医疗
                    po.setType(4);
                    break;
                case "sport": //体育
                    po.setType(5);
                    break;
                case "community": //社区
                    po.setType(6);
                    break;
                case "publicservice": //公共服务
                    po.setType(7);
                    break;
                case "socialorganization": //社会组织
                    po.setType(8);
                    break;
                case "enterprise": //企业
                    po.setType(9);
                    break;
            }
        }else{
            po.setType(0);
        }
        if((po.getArea()!=null && po.getArea()=="") || (po.getName()!=null && po.getName()=="")|| (po.getNameLike()!=null && po.getNameLike()=="")){
            return new DataResponseVo<Object>(StatusCode.PARAM_ERROR.getStatusCode(),StatusCode.PARAM_ERROR.getStatusMessage());
        }
        List<BaseAddressResponsePo> listVos = new ArrayList<>();
        int count = baseAddressService.selectAddressByConditionsCount(po);
        List<BaseAddress> list = baseAddressService.selectAddressByConditions(po);

        if(list.size()>0){
            for(BaseAddress aa:list){
                Group group = groupService.selectById(Integer.parseInt(aa.getGroupId().toString()));
                listVos.add(BaseAddressResponsePo.buildVO(aa, group));
            }
        }

        Page<BaseAddressResponsePo> page = new Page<>();
        page.setData(listVos);
        page.setTotalCount(count);

        return new DataResponseVo<>(StatusCode.SUCCESS.getStatusCode(), StatusCode.SUCCESS.getStatusMessage(),page);
    }

    //基地详情
    @ResponseBody
    @RequestMapping(value = "/queryAddressDetail",method = RequestMethod.POST,produces = "application/json; charset=UTF-8")
    public DataResponseVo<Object> queryAddressDetail(@RequestBody BaseAddressRequestVo vo) {
        if(vo.getId()==null || vo.getId()==0){
            return new DataResponseVo<Object>(StatusCode.PARAM_ERROR.getStatusCode(),StatusCode.PARAM_ERROR.getStatusMessage());
        }
        BaseAddress baseAddress = baseAddressService.selectById(vo.getId());
        Group group = groupService.selectById(Integer.parseInt(baseAddress.getGroupId().toString()));
        BaseAddressResponsePo baseResponsePo = BaseAddressResponsePo.buildVO(baseAddress, group);
        return new DataResponseVo<>(StatusCode.SUCCESS.getStatusCode(), StatusCode.SUCCESS.getStatusMessage(),baseResponsePo);
    }


}
